package com.itm.eventos.utils;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.swing.UIManager;

import org.apache.log4j.Logger;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


public class Utilidades {

	private final static Logger logger = Logger.getLogger(Utilidades.class);
	private static Properties propiedadesServer;
	private static String path = "";
	private static String pathserver = "";
	private static String tmppathserver = "";
	
	static {
		try {
			obtenerPropiedades();
			pathserver = 
				"\\\\" + propiedadesServer.getProperty(Constantes.SERVER_IP) + 
				"\\" + propiedadesServer.getProperty(Constantes.SERVER_DIRECTORY);
			tmppathserver = 
				"\\\\" + propiedadesServer.getProperty(Constantes.SERVER_IP) + 
				"\\" + propiedadesServer.getProperty(Constantes.SERVER_TMPDIRECTORY);
			path = getPathProyecto();	
		} 
		catch (IOException e) {logger.error("Error al obtener la ruta de ejecucion: " + e.getMessage());}
	}

	public static String getFechaActual() { 
		return new SimpleDateFormat(Constantes.FORMATO_FECHA).format(new Date()).toString();
	}
	
	public static String getPathProyecto() throws IOException {
		return new java.io.File(".").getCanonicalPath()+"/";
	}

	public static String getPathServer() {
		return pathserver;
	}

	public static String getTmpPathServer() {
		return tmppathserver;
	}
	
	public static String guardarJPG(Image imagen) throws RuntimeException{
		String ruta = null;
		try {
			ruta = 
				Constantes.RUTA_CAPTURAS + "/" + Constantes.LOCATION_FOTOS + "/" +
				new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date()).toString() +
				Constantes.EXT_CAPTURA_WEB;
			
			FileOutputStream salida = new FileOutputStream(path + ruta);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(salida);
			BufferedImage bi = toBufferedImage(imagen);
			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
			param.setQuality(1.0f, false);
			encoder.setJPEGEncodeParam(param);
			encoder.encode(bi);
			salida.close();
		} catch (Exception e) {
			logger.error("Fichero no encontrado:" + e.getMessage());
		}
	
		copyFileToRemoteLocation(
			path + ruta, 
			tmppathserver+ruta.substring(ruta.indexOf("/")));
		
		return ruta;
	}
	
	private static BufferedImage toBufferedImage(Image imagen) {
		int anchura = imagen.getWidth(null);
		int altura = imagen.getHeight(null);
		int tipo = BufferedImage.TYPE_INT_RGB;
		BufferedImage bi = new BufferedImage(anchura, altura, tipo);
		Graphics2D g2 = bi.createGraphics();
		g2.drawImage(imagen, null, null);
		g2.dispose(); //Libera memoria
		return bi;
	}
	
	/**
	 * Backup fichero 
	 */
	public static void backUpFile(String rutaOrigen, String rutaDestino){
		File carpeta = null;
		File fich = null;
		
		try {
			carpeta = new File(rutaOrigen);
			if( !carpeta.exists()){
				carpeta.mkdirs();
			}
			carpeta =  new File(rutaOrigen+"/");
			carpeta.mkdir();
			fich = new File(rutaDestino);
			copyfile(fich.getAbsolutePath(), carpeta.getAbsolutePath()+"/"+fich.getName());
		} catch (Exception e) {
		}
	}

	/**
	 * Copiado fichero de un origen a un destino
	 * @param srFile
	 * @param dtFile
	 */
	private static void copyfile(String srFile, String dtFile) {
		try {
			File f1 = new File(srFile);
			File f2 = new File(dtFile);
			InputStream in = new FileInputStream(f1);

			OutputStream out = new FileOutputStream(f2);

			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
			logger.info("Fichero copiado.");
		} catch (FileNotFoundException ex) {
			logger.error(ex.getMessage() + " En el directorio especificado.");
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
	}
	
	public static void copyFileToRemoteLocation(String rutaOrigen, String rutaDestino) {
		try {
			InputStream in = new FileInputStream(new File(rutaOrigen));
			File destFile = new File(rutaDestino);
			OutputStream out = new FileOutputStream(destFile);
			
			// Transfer bytes from in to out
			byte[] buf = new byte[1024];
			int len;
			
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
		
			in.close();
			out.close();
			
			moveFileRemoteLocation(destFile);

		} catch (IOException e) {
			logger.error("Problema al copiar el fichero en la ruta remota:" + e.getMessage());
		}
	}

	// Move file to new directory cause the cron service on server
	private static void moveFileRemoteLocation(File tmpfile) {
		String rutaorig = tmpfile.getAbsolutePath();
		File destFile = new File(rutaorig.replaceFirst(
			propiedadesServer.getProperty(Constantes.SERVER_TMPDIRECTORY), 
			propiedadesServer.getProperty(Constantes.SERVER_DIRECTORY)));
		boolean success = tmpfile.renameTo(destFile);
		if (!success) {
			logger.error("Problemas al mover el fichero de la carptea temporal");
		}
	}

	private static void obtenerPropiedades() {
		try {
			String rutaPropiedades = Constantes.RUTA_CONF + "/" + Constantes.FICH_PROP_SERVER;
			propiedadesServer = new Properties();
			propiedadesServer.load(new FileInputStream(rutaPropiedades));
		} catch (FileNotFoundException e1) {
		} catch (IOException e) {}
	}
	
	public static void establecerlookandfeel() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}